#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------
#Author:  LJ
#Email:   admin@attacker.club

#Last Modified: 2018-07-05 11:39:06
#Description: py2
# --------------------------------------



import telnetlib
import re,time,datetime
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


DEBUG =  False  # False 读取host.txt列表主机






def run(host):
    now = datetime.datetime.now()
    today = now.strftime('%Y%m%d')
    logdate = now.strftime("%b %d %H:%M:%S")
    try:
        telnetsession = telnetlib.Telnet(host,timeout=10)  # 实例化telnet对象，建立一个主机连接
        #print (telnetsession.timeout)
        
        #telnetsession.set_debuglevel(1) # 开启调试，按需开启，方便判断

        telnetsession.write(user + "\n")
        telnetsession.read_very_lazy()
        telnetsession.write(pwd + "\n")
        #登录认证

        # 如果登录成功，则出现类似<R1>,使用UsermodTag来进行捕获
        response = telnetsession.read_until('>')
        devname = re.findall(r'\<(.*)\>.*',response)[0] #正则导入主机名
        #print(devname) 
        if response.find('>') > -1:
            print("INFO:\t%s\t[\033[1;32m%s\033[0m] Login successfully　..." % (logdate, host))

            for cmdline in cmdlist:

                telnetsession.write("%s\n" % cmdline)
                telnetsession.read_very_lazy()

            


            response = telnetsession.read_until('changed') 
            #read_until()来判断缓冲区中的数据是否有想要的内容，如果没有就等待
            telnetsession.write("put startup.cfg %s-%s-%s.cfg\n" % (devname,host,today))
            telnetsession.close()
        



        


    except Exception as e:
        print(e, type(e))
    finally:
       
        # 执行完毕后，关闭连接
        
        print("INFO:\t%s\t[\033[1;32m%s\033[0m] Session Close　..." % (logdate, host))
        telnetsession.read_until('complete')
        
        telnetsession.write("quit\n")
        telnetsession.close()
        

if __name__ == '__main__':

    cmdlist = [
      "ftp.conf 36.27.209.76",
      "ftp.conf",
      "ftpxxx",
      "cd net_config"
    ]


    ### 配置登录信息
    user = 'admin'
    pwd = raw_input("输入密码：")
    host = '192.168.16.2'

    if not DEBUG:
        with open("host.txt") as f:

            for host in f:
                h = host.strip()
                run(h)

            
    else: #测试
        run(host)



